﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.UI.Application.ActionResults;
using MethodWorx.CMS.Providers;
using MethodWorx.CMS.Plugins.ActionResults;
using MethodWorx.Core.DomainModel;

namespace MethodWorx.CMS.Plugins.ViewManagement
{
    public class ViewManagementController : Controller
    {
        private IdeExtension extension;
        private ContentService content;
        private StaticViewService service;

        public ViewManagementController(ICmsDataProvider provider, IdeExtension extension, ContentService content)
        {
            this.extension = extension;
            this.content = content;
            this.service = new StaticViewService(provider);
        }

        [HttpGet]
        public ActionResult Create(string searchString, bool? pages)
        {
            if(!string.IsNullOrEmpty(searchString))
            {
                //
                //  ok, lets find what we need
                List<object> values = new List<object>();
                if (pages.Value)
                {
                    foreach (
                        var page in content.GetAllPages().Where(p => p.Name.ToLower().Contains(searchString.ToLower())))
                    {
                        values.Add(new {Id = page.Id, Name = page.Name});
                    }
                }
                else
                {
                    foreach (
                        var contentItem in content.GetAllConentItems().Where(p => p.Name.ToLower().Contains(searchString.ToLower())))
                    {
                        values.Add(new { Id = contentItem.Id, Name = contentItem.Name + " (" + contentItem.Page.Name + ")" });
                    }
                }
                return Json(values.ToArray(), JsonRequestBehavior.AllowGet);
            }
            else
                return new EmbeddedViewResult(this.extension.WebEditor);
        }

        [HttpPost]
        public ActionResult Create(string submit, StaticView staticView, Guid [] ids)
        {
            switch((submit ?? "").ToLower())
            {
                case "cancel":
                    return new CloseDialogResult();
                    break;
                default:
                    if(this.ModelState.IsValid)
                    {
                        //
                        //  ok, we are valid
                        //
                        staticView.Ids = ids;
                        this.service.Create(staticView);
                        return new RefreshTreeNodeResult().And(new CloseDialogResult());
                    }
                    else
                    {
                        return new EmbeddedViewResult(this.extension.WebEditor, new ViewManagementModel()
                                                                                    {
                                                                                        StaticView = staticView
                                                                                    });
                    }
                    break;
            }
        }

        [HttpGet]
        public ActionResult Edit(Guid id, string searchString, bool? pages)
        {
            var view = service.GetById(id);
            if (view == null)
                throw new BusinessRuleException("View not found");

            var model = new ViewManagementModel()
                        {
                            StaticView = view,
                            Names= GetNames(view)
                        };

            if (!string.IsNullOrEmpty(searchString))
            {
                //
                //  ok, lets find what we need
                List<object> values = new List<object>();
                if (pages.Value)
                {
                    foreach (
                        var page in content.GetAllPages().Where(p => p.Name.ToLower().Contains(searchString.ToLower())))
                    {
                        values.Add(new { Id = page.Id, Name = page.Name });
                    }
                }
                else
                {
                    foreach (
                        var contentItem in content.GetAllConentItems().Where(p => p.Name.ToLower().Contains(searchString.ToLower())))
                    {
                        values.Add(new { Id = contentItem.Id, Name = contentItem.Name + " (" + contentItem.Page.Name + ")" });
                    }
                }
                return Json(values.ToArray(), JsonRequestBehavior.AllowGet);
            }
            else
                return new EmbeddedViewResult(this.extension.WebEditor, model);
        }

        private Dictionary<Guid, string> GetNames(StaticView view)
        {
            Dictionary<Guid, string> names = new Dictionary<Guid,string>();
            if (view.Pages)
            {
                foreach (var id in view.Ids)
                {
                    var page = this.content.GetPageById(id);
                    if (page != null)
                        names.Add(id, page.Name);
                    else
                        names.Add(id, "Deleted");
                }
            }
            else
            {
                foreach (var id in view.Ids)
                {
                    var page = this.content.GetContentItemById(id);
                    if (page != null)
                        names.Add(id, page.Name);
                    else
                        names.Add(id, "Deleted");
                }
            }

            return names;
        }

        [HttpPost]
        public ActionResult Edit(Guid id, string submit, StaticView staticView, Guid[] ids)
        {
            var view = service.GetById(id);
            if (view == null)
                throw new BusinessRuleException("View not found");

            switch ((submit ?? "").ToLower())
            {
                case "cancel":
                    return new CloseDialogResult();
                    break;
                default:
                    if (this.ModelState.IsValid)
                    {
                        //
                        //  ok, we are valid
                        //
                        staticView.Ids = ids;
                        this.service.Save(id, staticView);
                        return new RefreshTreeNodeResult().And(new CloseDialogResult());
                    }
                    else
                    {
                        return new EmbeddedViewResult(this.extension.WebEditor, 
                            new ViewManagementModel()
                        {
                            StaticView = staticView,
                            Names = GetNames(view)
                        });
                    }
                    break;
            }
        }
    }
}
